package com.tiance.demo.service.mysql.analyzer.pageindex;

import com.tiance.demo.service.mysql.utils.ByteUtils;
import com.tiance.demo.service.mysql.bo.pageindex.RecordHead;

public class RecordHeadAnalyzer {

    public static RecordHead analyse(byte[] bytes) {
        RecordHead recordHead = new RecordHead();
        recordHead.setBytes(bytes);

        analyseReserve1(recordHead);
        analyseReserve2(recordHead);
        analyseDeleteMask(recordHead);
        analyseMinRecMask(recordHead);
        analyseNOwned(recordHead);
        analyseHeapNo(recordHead);
        analyseRecordType(recordHead);
        analyseNextRecord(recordHead);

        return recordHead;
    }

    private static void analyseReserve1(RecordHead recordHead) {
        int reserve1 = recordHead.getBytes()[0] >> 7;
        recordHead.setReserve1(reserve1);
    }

    private static void analyseReserve2(RecordHead recordHead) {
        int reserve2 = recordHead.getBytes()[0] >> 6 & 0x1;
        recordHead.setReserve2(reserve2);
    }

    private static void analyseDeleteMask(RecordHead recordHead) {
        int deleteMask = recordHead.getBytes()[0] >> 5 & 0x1;
        recordHead.setDeleteMask(deleteMask);
    }

    private static void analyseMinRecMask(RecordHead recordHead) {
        int minRecMask = recordHead.getBytes()[0] >> 4 & 0x1;
        recordHead.setMinRecMask(minRecMask);
    }

    private static void analyseNOwned(RecordHead recordHead) {
        int minRecMask = recordHead.getBytes()[0] & 0x15;
        recordHead.setMinRecMask(minRecMask);
    }

    private static void analyseHeapNo(RecordHead recordHead) {
        int heapNo = recordHead.getBytes()[1] << 3 | recordHead.getBytes()[2] >> 3;
        recordHead.setHeapNo(heapNo);
    }

    private static void analyseRecordType(RecordHead recordHead) {
        int recordType = recordHead.getBytes()[2] & 0x7;
        recordHead.setRecordType(recordType);
    }

    private static void analyseNextRecord(RecordHead recordHead) {
        byte[] bytes = new byte[2];
        System.arraycopy(recordHead.getBytes(), 3, bytes, 0, 2);
        int nextRecord = ByteUtils.bytes2Int(bytes);
        recordHead.setNextRecord(nextRecord);
    }

}
